﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Drawing;
using System.Web.Security;
using System.Text.RegularExpressions;

namespace BugTacker.Common
{
    public static class CommonRoutines
    {
        #region consts

        const int sizeThumb = 69;

        #endregion

        #region framework

        public static string EnsureNotNull(object value)
        {
            if (value == null)
                return string.Empty;
            return value.ToString();
        }

        public static string EnsureMaxLength(string value, int maxLength)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
            else if (value.Length == 0)
                return value;
            else if (value.Length < maxLength)
                return value;
            else
                return value.Substring(0, maxLength);
        }

        public static Guid EnsureGuid(string value)
        {
            if (string.IsNullOrEmpty(value))
                return Guid.Empty;
            Guid result = Guid.Empty;
            Guid.TryParse(value, out result);
            return result;
        }

        public static int EnsureInt(string value)
        {
            if (string.IsNullOrEmpty(value))
                return (int)0;
            int result = (int)0;
            Int32.TryParse(value, out result);
            return result;
        }

        public static decimal EnsureDecimal(string value)
        {
            if (string.IsNullOrEmpty(value))
                return Decimal.Zero;
            decimal result = Decimal.Zero;
            Decimal.TryParse(value, out result);
            return result;
        }

        public static DateTime EnsureDateTime(string value)
        {
            if (string.IsNullOrEmpty(value))
                return DateTime.MinValue;
            DateTime result = DateTime.MinValue;
            DateTime.TryParse(value, out result);
            return result;
        }

        public static DateTime EnsureDateTime(object value)
        {
            if (value == null)
                return DateTime.MinValue;
            DateTime result = DateTime.MinValue;
            DateTime.TryParse(value.ToString(), out result);
            return result;
        }

        #endregion

        #region web

        public static string Encode(string value)
        {
            return HttpUtility.HtmlEncode(value);
        }

        public static string Decode(string value)
        {
            return HttpUtility.HtmlDecode(value);
        }

        public static string EncodeUrl(string value)
        {
            return HttpUtility.UrlEncode(value);
        }

        public static string DecodeUrl(string value)
        {
            return HttpUtility.UrlDecode(value);
        }

        private static string ServerVariables(string name)
        {
            return HttpContext.Current.Request.ServerVariables[name];
        }

        private static bool IsSSL()
        {
            if (HttpContext.Current.Request.IsSecureConnection)
                return true;
            else
                return false;
        }

        public static string GetHost()
        {
            string host = string.Empty;
            if (!IsSSL())
            {
                host = "http://";
            }
            else
            {
                host = "https://";
            }
            return (host + ServerVariables("HTTP_HOST"));
        }

        public static void DropDownSelectByValue(System.Web.UI.WebControls.DropDownList dropDown, object value)
        {
            dropDown.SelectedIndex = dropDown.Items.IndexOf(dropDown.Items.FindByValue(value.ToString()));
        }

        public static string GetPageName(HttpContext context)
        {
            string result = string.Empty;
            result = Path.GetFileName(context.Request.Path);
            return result;
        }

        #endregion

        #region scripts

        public static void RegisterScript(Page page, string script)
        {
            if (page != null)
            {
                ClientScriptManager csm = page.ClientScript;
                Type type = page.GetType();
                if (csm != null)
                {
                    if (!csm.IsStartupScriptRegistered(type, script))
                    {
                        csm.RegisterClientScriptInclude(type, script, (GetHost() + script));
                    }
                }
            }
        }

        public static void RegisterJQuery(Page page, string path)
        {
            RegisterScript(page, path + "jquery-1.4.1.min.js");
            RegisterScript(page, path + "jquery-1.4.1.js");
            RegisterScript(page, path + "jquery-1.4.1-vsdoc.js");
        }

        #endregion

        #region images

        public static bool IsImageFileExtension(HttpPostedFile file)
        {
            return new Regex(@"\.(jpg|jpeg|png|bmp|gif)$").IsMatch(System.IO.Path.GetExtension(file.FileName).ToLower());
        }

        public static byte[] GetBytesFromStream(Stream stream)
        {
            byte[] image = null;
            image = new byte[stream.Length];
            stream.Read(image, 0, (int)stream.Length);
            stream.Close();
            return image;
        }

        public static byte[] GetBytesFromPostedFile(HttpPostedFile file)
        {
            byte[] image = null;
            if (file == null)
                return null;
            else
            {
                image = new byte[file.InputStream.Length];
                file.InputStream.Read(image, 0, (int)file.InputStream.Length);
                file.InputStream.Close();
                return image;
            }
        }

        public static byte[] MakeThumb(byte[] fullsize)
        {
            Image iOriginal, iThumb;
            int targetH, targetW;

            iOriginal = Image.FromStream(new MemoryStream(fullsize));
            if (iOriginal.Height > iOriginal.Width)
            {
                targetH = sizeThumb;
                targetW = Convert.ToInt32(iOriginal.Width * (sizeThumb / iOriginal.Height));
            }
            else
            {
                targetW = sizeThumb;
                targetH = Convert.ToInt32(iOriginal.Height * (sizeThumb / iOriginal.Width));
            }
            iThumb = iOriginal.GetThumbnailImage(targetW, targetH, null, System.IntPtr.Zero);
            MemoryStream m = new MemoryStream();
            iThumb.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
            return m.GetBuffer();
        }

        public static byte[] MakeThumb(byte[] fullsize, int newwidth, int newheight)
        {
            Image iOriginal, iThumb;
            double scaleH, scaleW;

            Rectangle srcRect = new Rectangle();
            iOriginal = Image.FromStream(new MemoryStream(fullsize));
            scaleH = iOriginal.Height / newheight;
            scaleW = iOriginal.Width / newwidth;
            if (scaleH == scaleW)
            {
                srcRect.Width = iOriginal.Width;
                srcRect.Height = iOriginal.Height;
                srcRect.X = 0;
                srcRect.Y = 0;
            }
            else if ((scaleH) > (scaleW))
            {
                srcRect.Width = iOriginal.Width;
                srcRect.Height = Convert.ToInt32(newheight * scaleW);
                srcRect.X = 0;
                srcRect.Y = Convert.ToInt32((iOriginal.Height - srcRect.Height) / 2);
            }
            else
            {
                srcRect.Width = Convert.ToInt32(newwidth * scaleH);
                srcRect.Height = iOriginal.Height;
                srcRect.X = Convert.ToInt32((iOriginal.Width - srcRect.Width) / 2);
                srcRect.Y = 0;
            }
            iThumb = new Bitmap(newwidth, newheight);
            Graphics g = Graphics.FromImage(iThumb);
            //g.Clear(Color.Transparent);
            //g.Clear(Color.Black);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(iOriginal, new Rectangle(0, 0, newwidth, newheight), srcRect, GraphicsUnit.Pixel);
            MemoryStream m = new MemoryStream();
            iThumb.Save(m, System.Drawing.Imaging.ImageFormat.Png);
            return m.GetBuffer();
        }

        public static byte[] MakeThumb(byte[] fullsize, int maxwidth)
        {
            Image iOriginal, iThumb;
            double scale;

            iOriginal = Image.FromStream(new MemoryStream(fullsize));
            if (iOriginal.Width > maxwidth)
            {
                scale = iOriginal.Width / maxwidth;
                int newheight = Convert.ToInt32(iOriginal.Height / scale);
                iThumb = new Bitmap(iOriginal, maxwidth, newheight);
                MemoryStream m = new MemoryStream();
                iThumb.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
                return m.GetBuffer();
            }
            else
            {
                return fullsize;
            }
        }

        public static Image MakeImage(byte[] value)
        {
             MemoryStream ms = new MemoryStream(value);
             Image result = Image.FromStream(ms);
             return result;
        }

        #endregion

    }
}
